<?php

declare(strict_types=1);

namespace app\common\lib;

use Firebase\JWT\JWT;

class JwtUtil
{
    private static $instance;

    protected function __construct()
    {
    }

    public static function instance(): static
    {
        if (!self::$instance) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * @var string 密钥
     */
    private string $key = '';
    /**
     * @var string 签发者
     */
    private string $iss = '';
    /**
     * @var string 面向的用户
     */
    private string $aud = '';

    /**
     * @param string $key
     * @return JwtUtil
     */
    public function setKey(string $key): static
    {
        $this->key = $key;
        return $this;
    }

    /**
     * @param string $iss
     * @return JwtUtil
     */
    public function setIss(string $iss): static
    {
        $this->iss = $iss;
        return $this;
    }

    /**
     * @param string $aud
     * @return JwtUtil
     */
    public function setAud(string $aud): static
    {
        $this->aud = $aud;
        return $this;
    }

    /**
     * 生成token
     * @param int $uid 用户uid
     * @param int $expire 过期时间秒数
     * @return string
     */
    public function createToken(int $uid, int $expire): string
    {
        $now = time();
        $token = [
            'iss' => $this->iss, //签发者
            'aud' => $this->aud, //jwt所面向的用户
            'iat' => $now, //签发时间
            'nbf' => $now + 0, //在什么时间之后该jwt才可用
            'exp' => $now + $expire, //过期时间
            'data' => [
                'uid' => $uid
            ]
        ];
        return JWT::encode($token, $this->key);
    }

    /**
     * @param string $token
     * @return object
     * @throws \Exception
     */
    public function verify(string $token): object
    {
        $ret = JWT::decode($token, $this->key, ['HS256']);
        return $ret->data;
    }
}